package com.mai4j.maiadmin.service.impl;

import com.mai4j.maiadmin.model.dto.AdminMenuDescriptionDTO;
import com.mai4j.maiadmin.service.AdminMenuDescriptionService;
import com.mai4j.maiadmin.support.JooqProvider;
import com.mai4j.maiadmin.support.cache.CacheName;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.mai4j.maiadmin.generated.Tables.ADMIN_MENU_DESCRIPTION;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
@Service
public class AdminMenuDescriptionServiceImpl implements AdminMenuDescriptionService {

    @Cacheable(value = CacheName.DATA, key = "'adminmenu:description:' + #adminMenuId")
    @Override
    public List<AdminMenuDescriptionDTO> get(Long adminMenuId) {
        return JooqProvider.dsl().selectFrom(ADMIN_MENU_DESCRIPTION)
                .where(ADMIN_MENU_DESCRIPTION.ADMIN_MENU_ID.eq(adminMenuId))
                .fetchInto(AdminMenuDescriptionDTO.class);
    }

    @CacheEvict(value = CacheName.DATA, key = "'adminmenu:description:' + #adminMenuId") // 清除对应的缓存
    @Override
    public void saveDescriptions(Long adminMenuId, List<AdminMenuDescriptionDTO> descriptions) {
        JooqProvider.dsl()
                .deleteFrom(ADMIN_MENU_DESCRIPTION)
                .where(ADMIN_MENU_DESCRIPTION.ADMIN_MENU_ID.eq(adminMenuId))
                .execute();
        for (AdminMenuDescriptionDTO descriptionDTO : descriptions) {
            JooqProvider.dsl().insertInto(ADMIN_MENU_DESCRIPTION)
                    .columns(
                            ADMIN_MENU_DESCRIPTION.ADMIN_MENU_ID,
                            ADMIN_MENU_DESCRIPTION.LANGUAGE_CODE,
                            ADMIN_MENU_DESCRIPTION.NAME
                    )
                    .values(adminMenuId,
                            descriptionDTO.getLanguageCode(),
                            descriptionDTO.getName())
                    .execute();
        }
    }
}
